package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.PackTemplet;
import com.scs.application.modules.base.entity.PackTempletItem;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.mapper.PackTempletItemMapper;
import com.scs.application.modules.base.service.PackTempletItemService;
import com.scs.application.modules.base.service.PackTempletService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class PackTempletItemServiceImpl extends BaseServiceImpl<PackTempletItemMapper, PackTempletItem> implements PackTempletItemService {

    @Autowired
    private PackTempletService packTempletService;

    @Autowired
    private MatrMapper matrMapper;


    public boolean saveOrUpdate(PackTempletItem entity) {

        List<PackTempletItem> items = this.list(Wrappers.<PackTempletItem>query().eq("pack_templet_id", entity.getPackTempletId()));

        long count = 0;

        if (entity.isNewRecord()) {
            count = items.stream().filter(item -> item.getMatrId().equalsIgnoreCase(entity.getMatrId())).count();
        } else {
            count = items.stream().filter(item ->
                    item.getMatrId().equalsIgnoreCase(entity.getMatrId()) && !item.getId().equalsIgnoreCase(entity.getId())
            ).count();
        }
        if (count > 0) {
            throw new BusinessException("模板中耗材不允许重复");
        }

        if(entity.getFlagMain()) { //如果是主耗材，判断是否有其他的主耗材
            items.stream().filter(item -> item.getFlagMain() && !item.getId().equals(entity.getId())).findAny().ifPresent(item -> {
                throw new BusinessException("模板中只能存在一种主耗材");
            });
        }

        boolean success = super.saveOrUpdate(entity);

        String packTempletId = entity.getPackTempletId();
        updatePackTempletAmount(packTempletId);
        return success;
    }



    @Override
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<String> packTempletIds = this.listObjs(Wrappers.<PackTempletItem>query()
                        .select("pack_templet_id" ).in("id" , idList).groupBy("pack_templet_id"),
                v -> v.toString());

        boolean success = super.removeCascadeByIds(idList);

        for (String packTempletId : packTempletIds) {
            updatePackTempletAmount(packTempletId);
        }

        return success;
    }

    /**
     * 重新计算模板价格
     * @param packTempletId
     */
    private void updatePackTempletAmount(String packTempletId) {
        List<PackTempletItem> pack_templet_id = this.list(Wrappers.<PackTempletItem>query().eq("pack_templet_id", packTempletId));
        Double amount = pack_templet_id
                .stream().mapToDouble(pack -> pack.getAmount() == null ? 0d : pack.getAmount()).sum();

        PackTemplet packTemplet = packTempletService.getById(packTempletId);
        if(packTemplet == null){
            return;
        }
        packTempletService.update(Wrappers.<PackTemplet>update().set("amount", amount).eq("id", packTempletId));
//        packTempletService.updateCascadeById(packTemplet);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateByMatrId(Collection<? extends Serializable> idList) {
        List<PackTempletItem> packTempletItems = this.list(Wrappers.<PackTempletItem>query().in("matr_id", idList));
        for (PackTempletItem s : packTempletItems) {
            Matr matr = matrMapper.selectById(s.getMatrId());
            if (matr == null){
                throw new BusinessException("相关联的耗材不存在");
            }
            s.setAmount(matr.getSkuPrice()*s.getSkuQty());
            boolean ok = this.updateById(s);
            if (ok){
                Map<String, Object> map = this.getMap(new QueryWrapper<PackTempletItem>().select("sum(amount) as amount")
                        .eq("pack_templet_id", s.getPackTempletId()));
                packTempletService.update(Wrappers.<PackTemplet>update()
                        .set("amount", map.get("amount") == null ? 0 : map.get("amount"))
                        .eq("id", s.getPackTempletId()));
            }
        }
        return true;
    }


    /**
     * @Description：科室请领需求批量操作
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchUser(List<PackTempletItem> entityList) {
        List<String> matrIdList = entityList.stream().map(PackTempletItem::getMatrId).collect(Collectors.toList());
        Map<String,Matr> matrMap = matrMapper.selectList(Wrappers.<Matr>query().in("id",matrIdList)).stream().collect(Collectors.toMap(Matr::getId,ob -> ob));
        Map<String,PackTempletItem> packTempletItemDbMap = baseMapper.selectList(Wrappers.<PackTempletItem>query().eq("pack_templet_id",entityList.get(0).getPackTempletId())).stream().collect(Collectors.toMap(PackTempletItem::getMatrId,ob -> ob));
        if (matrMap == null || matrMap.keySet().size() < 1) throw new BusinessException("所操作耗材已被删除，请重新选择");

        List<PackTempletItem> entityListSave = new ArrayList<PackTempletItem>();
        entityList.stream().forEach(applyItem -> {
            Matr matr  = matrMap.get(applyItem.getMatrId());
            if (matr == null ) throw new BusinessException("所操作耗材【%s】已被删除，请重新选择",matr.getName());
            if (StringUtils.isBlank(matr.getSkuUnit())) throw new BusinessException("所操作耗材【%s】缺少单品单位已被删除，请重新选择",matr.getName());
            if (matr.getSkuPrice() == null || matr.getSkuPrice() <= 0 ) throw new BusinessException("所操作耗材【%s】单品价格为0，请重新选择",matr.getName());
            if (packTempletItemDbMap !=null && packTempletItemDbMap.containsKey(applyItem.getMatrId())) throw new BusinessException("所操作耗材【%s】已添加，请重新选择",matr.getName());
            BeanUtils.copyProperties(matr,applyItem);
            applyItem.setMatrId(matr.getId()).setMatrName(matr.getName()).setMatrSpec(matr.getSpec());
            applyItem.setPackageUnit(matr.getSkuUnit()).setPackageQty(1d).setPackageRate(1d).setAmount(matr.getSkuPrice()).setSkuQty(1d).setId(null);
            entityListSave.add(applyItem);
        });
        for (PackTempletItem templetItem : entityListSave) {
            this.save(templetItem);
        }
//        this.saveBatch(entityListSave);
        this.updatePackTempletAmount(entityList.get(0).getPackTempletId());
    }
}
